import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMatchList, deleteMatch, batchDeleteMatches, type Match, type MatchQueryParams } from '@/api/matches'
import type { VxeGridProps } from 'vxe-table'

// 响应式数据
export const loading = ref(false)
export const tableRef = ref()

// 搜索表单
export const searchForm = reactive({
  tournament_name: '',
  tournament_intro: '',
  tournament_score: '',
  remarks: '',
  tournament_type: '',
  status: '',
  dateRange: []
})

// 分页配置
export const pagerConfig = reactive({
  enabled: true,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
  layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'Total']
})

// 表格数据
export const tableData = ref<Match[]>([])

// 分页信息
export const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  pages: 0
})

// 注意：loadData方法已被VXE Grid的proxyConfig替代，不再需要手动调用

// 方法
export const goToDetails = (row: MatchRowVO, router: any) => {
  router.push({
    path: '/matches/details',
    query: { id: row.id }
  })
}

export const goToAdd = (router: any) => {
  router.push('/matches/add')
}

// 刷新表格数据
export const refreshTable = () => {
  if (tableRef.value) {
    tableRef.value.commitProxy('query')
  }
}

export const handleBatchDelete = async () => {
  const selectedRows = tableRef.value?.getCheckboxRecords()
  
  if (!selectedRows || selectedRows.length === 0) {
    ElMessage.warning('请选择要删除的赛事')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.length} 条赛事吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedRows.map((row: Match) => row.id!).filter(Boolean)
    const response = await batchDeleteMatches(ids)
    
    if (response.success) {
      ElMessage.success(`成功删除 ${response.data.deletedCount} 条赛事`)
      // 刷新VXE Grid数据
      if (tableRef.value) {
        tableRef.value.commitProxy('query')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
    }
  }
}

export const handleEdit = (row: MatchRowVO, router: any) => {
  router.push({
    path: '/matches/add',
    query: { id: row.id, mode: 'edit' }
  })
}

export const handleDelete = async (row: MatchRowVO) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除赛事 "${row.tournament_name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteMatch(row.id)
    
    if (response.success) {
      ElMessage.success('删除成功')
      // 刷新VXE Grid数据
      if (tableRef.value) {
        tableRef.value.commitProxy('query')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

export const handleSearch = async () => {
  // 刷新VXE Grid数据
  if (tableRef.value) {
    tableRef.value.commitProxy('query')
  }
}

export const handleReset = () => {
  Object.assign(searchForm, {
    tournament_name: '',
    tournament_intro: '',
    tournament_score: '',
    remarks: '',
    tournament_type: '',
    status: '',
    dateRange: []
  })
  // 重置后刷新数据
  if (tableRef.value) {
    tableRef.value.commitProxy('query')
  }
}

export const handlePageChange = async (params: any) => {
  pagination.current = params.currentPage
  pagination.pageSize = params.pageSize
  // VXE Grid会自动处理分页，不需要手动调用loadData
}

export const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    completed: 'success',
    ongoing: 'warning',
    pending: 'info',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

export const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    completed: '已结束',
    ongoing: '进行中',
    pending: '待开始',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}
interface MatchRowVO {
  id: number
  tournament_name: string
  tournament_type: string
  tournament_score: number
  tournament_intro: string
  venue: string
  match_time: string
  status: string
  remarks: string
  created_at: string
  updated_at: string
}

// 使用真实API的分页查询
export const findPageList = async (pageSize: number, currentPage: number) => {
  try {
    loading.value = true
    
    const params: MatchQueryParams = {
      page: currentPage,
      limit: pageSize,
      tournament_name: searchForm.tournament_name || undefined,
      tournament_intro: searchForm.tournament_intro || undefined,
      tournament_score: searchForm.tournament_score ? Number(searchForm.tournament_score) : undefined,
      remarks: searchForm.remarks || undefined,
      tournament_type: searchForm.tournament_type || undefined,
      status: searchForm.status || undefined,
      start_date: searchForm.dateRange?.[0] || undefined,
      end_date: searchForm.dateRange?.[1] || undefined
    }
    
    const response = await getMatchList(params)
    
    if (response.success) {
      return {
        result: response.data.list as MatchRowVO[],
        page: {
          total: response.data.pagination.total
        }
      }
    } else {
      throw new Error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('查询数据失败:', error)
    ElMessage.error('获取数据失败')
    return {
      result: [],
      page: {
        total: 0
      }
    }
  } finally {
    loading.value = false
  }
}

export const gridOptions = reactive<VxeGridProps<MatchRowVO>>({
  border: true,
  height: 500,
  pagerConfig: {
    enabled: true,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100],
    layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'Total']
  },
  proxyConfig: {
    showLoading: false,
    response: {
      result: 'result', // 配置响应结果列表字段
      total: 'page.total' // 配置响应结果总页数字段
    },
    ajax: {
      query: ({ page }) => {
        return findPageList(page.pageSize, page.currentPage)
      }
    }
  },
  columns: [
    {
      type: 'checkbox',
      width: 60
    },
    {
      type: 'seq',
      width: 60
    },
    {
      field: 'tournament_name',
      title: '赛事名称',
      width: 150
    },
    {
      field: 'tournament_type',
      title: '赛事类型',
      width: 120
    },
    {
      field: 'tournament_score',
      title: '赛事积分',
      width: 100
    },
    {
      field: 'tournament_intro',
      title: '赛事简介',
      width: 120
    },
    {
      field: 'venue',
      title: '赛事地点',
      width: 120
    },
    {
      field: 'match_time',
      title: '比赛时间',
      width: 180
    },
    {
      field: 'status',
      title: '状态',
      width: 100,
      formatter: ({ cellValue }) => {
        const statusMap: Record<string, string> = {
          completed: '已结束',
          ongoing: '进行中',
          pending: '待开始',
          cancelled: '已取消'
        }
        return statusMap[cellValue] || '未知'
      }
    },
    {
      title: '操作',
      width: 200,
      fixed: 'right',
      slots: { default: 'action' }
    }
  ]
})

// 注意：VXE Grid会自动处理数据加载，不需要onMounted